// pages/orderPay/orderPay.js
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var pay = require("../../services/pay");
let num = 0;
const App = getApp();
var intervalNum = 0;
Page({
    /**
     * 页面的初始数据
     */
    data: {
        wxAddress:null,
        isMail:false,
        isGroupBuying:false,
        imageIconList: {
            promise: "/static/images/orderpay/promise.png",
            bags: "/static/images/orderpay/bags.png",
            moreGray: "/static/images/orderpay/more-gray.png",
            moreRed: "/static/images/orderpay/more-red.png",
        },
        showDialog: false,
        nextDate: null,
        commodityList: [], //购买商品
        exchangeCommodityList: [], //换购商品
        selectedExchangeList: [], //已选中的换购商品
        payAmount: 0,
        scoreAmount: 0,
        totalAmount: 0,
        savingAmount: 0,
        couponAmount: 0,
        isCreatingOrder: false, //防重复触碰支付装置
        memberLeaderObj: {},
        userInfo: {},
        isShowCoupon: false,
        text: "",
        marqueePace: 1,//滚动速度
        marqueeDistance: 0,//初始滚动距离
        marquee_margin: 30,
        size:12,
        intervalText: 40, // 时间间隔
        length:"",
        windowWidth:""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const date = new Date();
        date.setDate(date.getDate()+1);
        const nextDate = util.formatTime(date.getTime() / 1000,'Y-M-D');
        const userInfo = wx.getStorageSync("userInfo");
        this.setData({
            nextDate,
            userInfo,
            isGroup: options.isGroup || false,
            activityType: options.activityType,
            isShowCoupon: (options.activityType == 0 || options.activityType == 3) ? true : false,
        });
        this.getPreOrder();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const orderGoodsList = wx.getStorageSync("orderGoodsList");
        this.setData({
            isMail:orderGoodsList[0].isMail
        })
        let memberLeaderObj = wx.getStorageSync('memberLeaderObj');
        console.log("App.globalData.memberLeaderObj", App.globalData.memberLeaderObj);
        let wxAddress = wx.getStorageSync('wxAddress');
        if(wxAddress){
            this.setData({
                wxAddress:wxAddress
            })
        }
        this.setData({
            memberLeaderObj: memberLeaderObj
        })

        this.getAddressInfoList();
        this.getPayBanner()
    },
    scrolltxt: function () {
      var that = this;
      var length = that.data.length;//滚动文字的宽度
      var windowWidth = that.data.windowWidth-20;// 当前显示区域的宽度
      if (length > windowWidth){
        intervalNum =  setInterval(function () {
          var maxscrollwidth = length + that.data.marquee_margin;//滚动的最大宽度，文字宽度+间距，如果需要一行文字滚完后再显示第二行可以修改marquee_margin值等于windowWidth即可
          var crentleft = that.data.marqueeDistance;
          if (crentleft < maxscrollwidth) {//判断是否滚动到最大宽度
            that.setData({
              marqueeDistance: crentleft + that.data.marqueePace
            })
          }else {
            //console.log("替换");
            that.setData({
              marqueeDistance: 0 // 直接重新滚动
            });
            clearInterval(intervalNum);
            that.scrolltxt();
          }
        }, that.data.intervalText);
      }else{
        that.setData({ marquee_margin:windowWidth});//只显示一条不滚动右边间距加大，防止重复显示
      }
  },

    getPayBanner() {
      let that = this
      wx.showLoading({
          title: "正在加载...",
      });
      util.request(api.indexUrl.payBanner, {}, "GET")
          .then((res) => {
              wx.hideLoading();
              if(res.result == '' || res.result == null|| !res.result.title) return
              that.setData({
                text:res.result.title
              })
              var length = that.data.text.length * that.data.size;//文字长度
              var windowWidth = wx.getSystemInfoSync().windowWidth-20;// 当前显示区域的宽度
              that.setData({
                length: length,
                windowWidth: windowWidth
              });
              that.scrolltxt();// 第一个字消失后立即从右边出现
          })
          .catch((err) => {
              wx.hideLoading();
          });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    // 关闭优惠的弹窗
    dialogClose(){
        this.setData({
            showDialog: false
        })
    },
    dialogBuy(e){
        console.log("e", e.detail);
        const { isClose, item } = e.detail;
        this.setData({
            showDialog: false,
            selectedExchangeList: [item]
        })
        console.log("null", num++);
        this.getPreOrder(true);
    },
    // 确认订单信息
    getPreOrder(isSelectedExchange = false){
        // const data = this.getOrderParams();
        // util.request(api.orderUrl.preOrder, data, "POST").then((res) =>{
        //     console.log("res", res);
        //     const data = res.result;
        //     let showDialog = false;
        //     if(data.exchangeCommodityList.length && !isSelectedExchange){
        //         showDialog = true
        //     }
        //     this.setData({
        //         commodityList: data.commodityList,
        //         exchangeCommodityList: data.exchangeCommodityList,
        //         payAmount: data.payAmount,
        //         scoreAmount: data.scoreAmount,
        //         totalAmount:data.totalAmount,
        //         savingAmount: data.savingAmount,
        //         couponAmount: data.couponAmount,
        //         showDialog
        //     })
        // })
        console.log(111,this.data)
        const {activityType} = this.data;
        if(activityType == 3 || activityType == 4){
            // 老流程
            this.oldPreOrderRequest(isSelectedExchange);
        }else{
            // 新流程
            this.newPreOrderRequest()
        }
    },
    // 确认订单和创建订单参数
    getOrderParams(params){
        const list = wx.getStorageSync("orderGoodsList"),
            commodityList = [],
            selectedExchangeList = this.data.selectedExchangeList,
            memberLeaderObj = this.data.memberLeaderObj;
        let leaderId = 0,
            addressId = 1;
        list.length && list.forEach(item=>{
            commodityList.push({
                commodityId: item.commodityId,
                quantity: item.quantity
            })
        })
        // 如果有勾选换购商品
        if(selectedExchangeList.length){
            commodityList.push({
                commodityId: selectedExchangeList[0].commodityId,
                quantity: 1
            })
        }
        if(memberLeaderObj.memberLeaderId){
            leaderId = memberLeaderObj.memberLeaderId;
            addressId = memberLeaderObj.id;
        }
        let defaultParams = {
            addressId,
            buyer: this.data.userInfo.nikeName,
            commodityList,
            isExchange: true,
            leaderId,
            phone: this.data.userInfo.phone,
            remark: ""
        };
        return Object.assign(defaultParams, params);
    },
    // 确认拼团订单和创建订单参数
    getGrouponOrderParams(params){
        const list = wx.getStorageSync("orderGoodsList"),
            commodityList = [],
            selectedExchangeList = this.data.selectedExchangeList,
            memberLeaderObj = this.data.memberLeaderObj;
        let leaderId = 0,
            addressId = 1;
        list.length && list.forEach(item=>{
            commodityList.push({
                commodityId: item.commodityId,
                quantity: item.quantity
            })
        })
        // 如果有勾选换购商品
        if(selectedExchangeList.length){
            commodityList.push({
                commodityId: selectedExchangeList[0].commodityId,
                quantity: 1
            })
        }
        let address = '';
        if(this.data.wxAddress){
            address = this.data.wxAddress.provinceName+''+this.data.wxAddress.cityName+this.data.wxAddress.countyName+this.data.wxAddress.detailInfo+this.data.wxAddress.userName
        }
        let defaultParams = {
            address:address,
            addressId:0,
            buyer: this.data.userInfo.nikeName,
            commodityList,
            isExchange: true,
            leaderId:0,
            phone: this.data.wxAddress.telNumber,
            remark: "",
            singleBuy:true,
        };
        if(list[0].parentOrderId){
            defaultParams.parentOrderId = list[0].parentOrderId;
        }
        return Object.assign(defaultParams, params);
    },
    // 创建订单
    createOrder(){

        const {activityType} = this.data;
        if(activityType == 3 || activityType == 4){
            // 老流程
            this.oldCreateORder();
        }else{
            // 新流程
            this.newCreateOrder();
        }
    },
    getWxAddress(){
        wx.getSetting({
            success: (result)=>{
            const scopeAddress = result.authSetting["scope.address"]
            if(scopeAddress===true||scopeAddress===undefined){
                wx.chooseAddress({
                    success: (result)=>{
                        wx.setStorageSync('wxAddress', result)
                        this.setData({
                            wxAddress:result
                        })
                    },
                });
            }
            else{
                wx.openSetting({
                    success:(result)=>{
                        console.log(result)
                    }
                })
            }
            }
        });
    },
    // 老流程
        // 预判
    oldPreOrderRequest(isSelectedExchange = false){
        const data = this.getOrderParams();
        util.request(api.orderUrl.preOrder, data, "POST").then((res) =>{
            console.log("res", res);
            const data = res.result;
            let showDialog = false;
            if(data.exchangeCommodityList.length && !isSelectedExchange){
                showDialog = true
            }
            this.setData({
                commodityList: data.commodityList,
                exchangeCommodityList: data.exchangeCommodityList,
                payAmount: data.payAmount,
                scoreAmount: data.scoreAmount,
                totalAmount:data.totalAmount,
                savingAmount: data.savingAmount,
                couponAmount: data.couponAmount,
                showDialog
            })
        })
    },
    // 新流程
        // 预判
        newPreOrderRequest(){
            const data = this.getOrderParams();
            const orderGoodsList = wx.getStorageSync("orderGoodsList");
            util.request(api.orderUrl.grouponPreOrder, data, "POST").then((res) =>{
                const data = res.result;
                this.setData({
                    commodityList: orderGoodsList,
                    exchangeCommodityList: data.exchangeCommodityList,
                    payAmount: data.payAmount,
                    scoreAmount: data.scoreAmount,
                    totalAmount:data.totalAmount,
                    savingAmount: data.savingAmount,
                    couponAmount: data.couponAmount,
                })
            })
        },
        // 创建订单
    oldCreateORder(){
        if(!this.data.memberLeaderObj.id){
            return wx.showToast({
                title: "请先选择提货点",
                icon: "none"
            });
        }
        if(this.data.isCreatingOrder){
            return wx.showToast({
                title: "正在创建",
                icon: "loading"
            });
        }
        this.setData({
            isCreatingOrder: true,
        })
        let _this = this;
        const data = this.getOrderParams();
        util.request(api.orderUrl.createOrder, data, "POST").then((res) =>{
            console.log("res");
            _this.goPayNormal(res.result.id,api.orderUrl.PayPrepayId);
        })
    },
    // 新流程
    newCreateOrder(){
        let _this = this;
        if(!this.data.wxAddress){
            return wx.showToast({
                title: "请先选择邮寄地址",
                icon: "none"
            });
        }
        if(this.data.isCreatingOrder){
            return wx.showToast({
                title: "正在创建",
                icon: "loading"
            });
        }
        this.setData({
            isCreatingOrder: true,
        })
        const data = this.getGrouponOrderParams();
        util.request(api.orderUrl.newcreateOrder, data, "POST").then((res) =>{
            _this.goPayGroupBuy(res.result.id,api.orderUrl.GrouponPay);
        })
    },
    goPayNormal(id,url){
        let _this = this;
        pay.payOrder(id,url).then(result=>{
            this.setData({
                isCreatingOrder: false,
            })
            //订阅消息
            let templIds = ['pHIuxSAvinesQtIMvCs1NVPCCXr6vxCKZV9GVn_LViE','Vr5H8d_O2uDBLfAdbieVhUzOHOACffHU_GG45hkkuEg','zVhtw38dMW9CdTpzWGHwGveYQrROitZsZoQ-7Lb8dt4']
            wx.requestSubscribeMessage({
                tmplIds: templIds,
                success (res) {
                    console.log(res)
                    wx.reLaunch({
                        url: "/pages/payDone/payDone"
                    })
                },
                fail (err) {
                    console.log(err)
                    wx.reLaunch({
                        url: "/pages/payDone/payDone"
                    })
                }
            })
        }).catch(err=>{
            wx.showModal({
                title: '低价不等人',
                confirmText:'继续支付',
                cancelText:'暂时放弃',
                content: '未支付订单会在10分钟后自动关闭，记得及时支付哟～',
                success (res) {
                  if (res.confirm) {
                      _this.goPayNormal(id,url);
                  } else if (res.cancel) {
                    wx.redirectTo({
                        url:'/pages/order/order'
                    });
                  }
                }
              })
        })
    },
    goPayGroupBuy(id,url){
        let _this = this;
        pay.payOrder(id,url).then(result=>{
            console.log("支付成功");
            this.setData({
                isCreatingOrder: false,
            })
            wx.reLaunch({
                url: "/pages/groupBuyingShare/groupBuyingShare?orderId="+res.result.id
            })
        }).catch(err=>{
            wx.showModal({
                title: '低价不等人',
                confirmText:'继续支付',
                cancelText:'暂时放弃',
                content: '未支付订单会在10分钟后自动关闭，记得及时支付哟～',
                success (res) {
                  if (res.confirm) {
                      _this.goPayGroupBuy(id,url);
                  } else if (res.cancel) {
                    wx.redirectTo({
                        url:'/pages/order/order'
                    });
                  }
                }
              })
        })
    },
    //获取提货点
    getAddressInfoList:function() {
        let _this = this;
        // let location = wx.getStorageSync('memberLeaderObj');
        // console.log(location)
        // if(location){
        //     _this.setData({
        //         memberLeaderObj:location
        //     })
        //     return
        // }
            wx.getLocation({
            type:'wgs84',
            success:function(res){

                util.request(api.findAddressInfoList+'?lat='+res.latitude+'&lon='+res.longitude).then(result=>{
                    const chooseItem = result.result.find(item => item.isChoose) || result.result[0];

                    _this.setData({
                        memberLeaderObj:chooseItem ,

                        markers: [{
                            id: "1",
                            latitude: chooseItem.lat,
                            longitude: chooseItem.lon,
                            width: 30,
                            height: 30,
                            iconPath: "http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/icon_position.png",
                            title: chooseItem.storeName + '|' + chooseItem.storeAddress

                        }],
                        circles: [{
                            latitude: chooseItem.lat,
                            longitude: chooseItem.lon,
                            color: '#FF0000DD',
                            fillColor: '#7cb5ec88',
                            radius: 100,
                            strokeWidth: 1
                        }]
                    })
                }).catch(err=>{
                    console.log(err)
                })

            },
            fail:function(err){
                console.log(err)
            }
        });

    },

});
